package com.xy.novelweb.interceptor;

import com.alibaba.fastjson.JSON;
import com.xy.novelweb.dao.NovelMapper;
import com.xy.novelweb.domain.Catalog;
import com.xy.novelweb.domain.Msg;
import com.xy.novelweb.domain.Reader;
import com.xy.novelweb.domain.ReaderBoughtCatalogs;
import com.xy.novelweb.service.NovelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class NovelReadInterceptor implements HandlerInterceptor {
		//	# 拦截器拦截 获取章节内容的ajax请求
		@Autowired
		private NovelMapper mapper;
		@Autowired
		private NovelService service;
		@Override
		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

				//	1、判断是否是ajax请求 不是-》拦截
				if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) { //如果是ajax请求响应头会有x-requested-with
						log.info("ajax请求被拦截");
						//	2、判断是否为vip章节 不是-》放行
						String novelName = request.getParameter("novelname");
						String catalogName = request.getParameter("catlogname");
						Catalog catalogMsg = mapper.getCatalogMsg(novelName, catalogName);
						if (catalogMsg.getVip()==0){
								log.info("不是vip章节");
								return true;
						}
						//	3、判断用户是否登录  未登录--》返回 未购买状态下的章节内容
						Reader reader = (Reader) request.getSession().getAttribute("user_reader");
						Msg<Object> msg = new Msg<>(false);
						String text = null;
						if (reader==null){
								//	5、未购买，查询章节内容，将内容前100个字返回页面
								text = service.getNovelCatlog(novelName, catalogName);
								int vipCatalogs = mapper.getUnBuyCatalogNum(novelName,"");
								int price = 15;
								msg.setMessage(price+":"+vipCatalogs*price);
								msg.setData(text.length()>=100?text.substring(0,100):text.substring(0,text.length()/2));
								returnJson(response, JSON.toJSONString(msg));
								log.info("未登录");
								return false;
						}else {
								//	4、登录的用户，根据用户查询是否购买本章节 是-》放行
								ReaderBoughtCatalogs boughtCatalog = mapper.selectOneReaderBoughtCatalog(reader.getNickName(), novelName, catalogName);
								if (boughtCatalog!=null){
										log.info("已登录，已购买章节");
										return true;
								}else {
										//	5、未购买，查询章节内容，将内容前100个字返回页面
										text = service.getNovelCatlog(novelName, catalogName);
										//查询未购买章节数
										int vipCatalogs = mapper.getUnBuyCatalogNum(novelName,reader.getNickName());
										int price = (15-reader.getVip());
										msg.setMessage(price+":"+vipCatalogs*price);
										msg.setData(text.length()>=100?text.substring(0,100):text.substring(0,text.length()/2));

										returnJson(response, JSON.toJSONString(msg));
										log.info("已登录，未购买章节");
										return false;
								}
						}
				}else {
						log.info("不是ajax请求");
						return false;
				}

		}

		//将json字符串写入请求
		private void returnJson(HttpServletResponse response, String json) throws Exception{
				PrintWriter writer = null;
				response.setCharacterEncoding("UTF-8");
				response.setContentType("text/html; charset=utf-8");
				try {
						writer = response.getWriter();
						writer.print(json);

				} catch (IOException e) {
						log.error("response error",e);
				} finally {
						if (writer != null)
								writer.close();
				}
		}
		@Override
		public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

		}

		@Override
		public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

		}
}
